<template>
    <div class="mind-map-container">
      <div class="toolbar">
        <button @click="addMainTopic" class="btn">Add Topic</button>
        <div class="color-picker">
          <label>Topic Color:</label>
          <input type="color" v-model="currentColor" />
        </div>
        <div class="line-style">
          <label>Line Style:</label>
          <select v-model="currentLineStyle">
            <option value="solid">Solid</option>
            <option value="dashed">Dashed</option>
          </select>
        </div>
      </div>
      
      <svg 
        ref="svgRef" 
        class="mind-map" 
        @mousedown="onSvgMouseDown"
        @mousemove="onSvgMouseMove"
        @mouseup="onSvgMouseUp"
        @mouseleave="onSvgMouseUp"
      >
        <!-- Connections between topics -->
        <g class="connections">
          <path 
            v-for="(connection, index) in connections" 
            :key="`connection-${index}`"
            :d="generatePath(connection)"
            :stroke="connection.color || '#666'"
            :stroke-dasharray="connection.style === 'dashed' ? '5,5' : ''"
            stroke-width="2"
            fill="none"
          />
        </g>
        
        <!-- Topics -->
        <g class="topics">
          <g 
            v-for="topic in topics" 
            :key="topic.id"
            class="topic"
            :transform="`translate(${topic.x}, ${topic.y})`"
            @mousedown.stop="startDrag(topic, $event)"
          >
            <rect 
              :width="topic.width" 
              :height="topic.height"
              :fill="topic.color"
              rx="5"
              ry="5"
              class="topic-rect"
              @click.stop="startEditing(topic, $event)"
            />
            
            <!-- Regular text display (shown when not editing) -->
            <text 
              v-if="editingTopic?.id !== topic.id"
              x="10" 
              y="25" 
              fill="#fff" 
              class="topic-text"
              @click.stop="startEditing(topic, $event)"
            >{{ topic.text }}</text>
            
            <!-- Inline editor (shown when editing this topic) -->
            <foreignObject 
              v-if="editingTopic?.id === topic.id"
              x="5" 
              y="5" 
              :width="topic.width - 10" 
              :height="topic.height - 10"
              @mousedown.stop
            >
              <div xmlns="http://www.w3.org/1999/xhtml" style="width: 100%; height: 100%;">
                <textarea 
                  ref="topicInputRef"
                  v-model="editingTopic.text" 
                  @keyup.enter="finishEditing"
                  @blur="finishEditing"
                  class="topic-input"
                  style="width: 100%; height: 100%;"
                  @click.stop
                ></textarea>
              </div>
            </foreignObject>
            
            <!-- Add subtopic button -->
            <g 
              class="add-button"
              @mousedown.stop="addSubTopic(topic)"
              :transform="`translate(${topic.width - 25}, 5)`"
            >
              <circle cx="10" cy="10" r="8" fill="#fff" />
              <text x="7" y="14" fill="#333" font-size="14">+</text>
            </g>
            
            <!-- Connect button -->
            <g 
              class="connect-button"
              @mousedown.stop="startConnection(topic, $event)"
              :transform="`translate(${topic.width - 25}, ${topic.height - 25})`"
            >
              <circle cx="10" cy="10" r="8" fill="#fff" />
              <text x="7" y="14" fill="#333" font-size="14">↗</text>
            </g>
          </g>
        </g>
        
        <!-- Active connection line -->
        <path 
          v-if="activeConnection.source"
          :d="generateActivePath()"
          stroke="#666"
          :stroke-dasharray="currentLineStyle === 'dashed' ? '5,5' : ''"
          stroke-width="2"
          fill="none"
        />
      </svg>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, nextTick } from 'vue';
  
  // 定义响应式数据
  const topics = ref([]);
  const connections = ref([]);
  const nextId = ref(1);
  const draggingTopic = ref(null);
  const dragOffset = ref({ x: 0, y: 0 });
  const activeConnection = ref({
    source: null,
    mouseX: 0,
    mouseY: 0,
  });
  const editingTopic = ref(null);
  const currentColor = ref("#4CAF50");
  const currentLineStyle = ref("solid");

  const topicInputRef = ref(null)
  const svgRef = ref(null)
  
  // 挂载时添加初始主题
  onMounted(() => {
    addMainTopic();
  });
  
  // 添加新的主主题
  const addMainTopic = () => {
    const id = nextId.value++;
    const newTopic = {
      id,
      text: `Topic ${id}`,
      x: 50,
      y: 50 + topics.value.length * 100,
      width: 150,
      height: 60,
      color: currentColor.value,
      parentId: null,
    };
  
    topics.value.push(newTopic);
    startEditing(newTopic);
  };
  
  // 为现有主题添加子主题
  const addSubTopic = (parentTopic) => {
    const id = nextId.value++;
    const newTopic = {
      id,
      text: `Subtopic ${id}`,
      x: parentTopic.x + 200,
      y: parentTopic.y,
      width: 150,
      height: 60,
      color: currentColor.value,
      parentId: parentTopic.id,
    };
  
    topics.value.push(newTopic);
  
    // 创建父主题和子主题之间的连接
    connections.value.push({
      sourceId: parentTopic.id,
      targetId: newTopic.id,
      style: currentLineStyle.value,
      color: "#666",
    });
  
    startEditing(newTopic);
  };
  
  // 开始编辑主题
  const startEditing = (topic, event) => {
    // 如果正在创建连接，则不开始编辑
    if (activeConnection.value.source) return;
  
    // 如果正在拖动，则不开始编辑
    if (draggingTopic.value) return;
  
    editingTopic.value = topic;
    nextTick(() => {
      const input = topicInputRef.value;
      if (input) {
        if (Array.isArray(input)) {
          input[0].focus();
          // 不选择所有文本以允许光标定位
        } else {
          input.focus();
          // 不选择所有文本以允许光标定位
        }
      }
    });
  };
  
  // 完成编辑主题
  const finishEditing = () => {
    editingTopic.value = null;
  };
  
  // 开始拖动主题
  const startDrag = (topic, event) => {
    // 如果正在编辑，则不开始拖动
    if (editingTopic.value?.id === topic.id) return;
    
    draggingTopic.value = topic;
    const rect = svgRef.value.getBoundingClientRect();
    dragOffset.value = {
      x: event.clientX - rect.left - topic.x,
      y: event.clientY - rect.top - topic.y,
    };
    event.preventDefault();
  };
  
  // 处理 SVG 鼠标移动以进行拖动
  const onSvgMouseMove = (event) => {
    if (draggingTopic.value) {
      const rect = svgRef.value.getBoundingClientRect();
      draggingTopic.value.x = event.clientX - rect.left - dragOffset.value.x;
      draggingTopic.value.y = event.clientY - rect.top - dragOffset.value.y;
    } else if (activeConnection.value.source) {
      const rect = svgRef.value.getBoundingClientRect();
      activeConnection.value.mouseX = event.clientX - rect.left;
      activeConnection.value.mouseY = event.clientY - rect.top;
    }
  };
  
  // 处理 SVG 鼠标抬起以结束拖动
  const onSvgMouseUp = () => {
    draggingTopic.value = null;
  
    // 检查是否连接到另一个主题
    if (activeConnection.value.source) {
      const targetTopic = findTopicAtPoint(activeConnection.value.mouseX, activeConnection.value.mouseY);
      if (targetTopic && targetTopic.id !== activeConnection.value.source.id) {
        // 创建新的连接
        connections.value.push({
          sourceId: activeConnection.value.source.id,
          targetId: targetTopic.id,
          style: currentLineStyle.value,
          color: "#666",
        });
      }
      activeConnection.value.source = null;
    }
  };
  
  // 处理 SVG 鼠标按下
  const onSvgMouseDown = (event) => {
    // 点击空白区域时完成编辑
    if (editingTopic.value) {
      finishEditing();
    }
  };
  
  // 开始从主题创建连接
  const startConnection = (topic, event) => {
    activeConnection.value.source = topic;
    const rect = svgRef.value.getBoundingClientRect();
    activeConnection.value.mouseX = event.clientX - rect.left;
    activeConnection.value.mouseY = event.clientY - rect.top;
    event.preventDefault();
  };
  
  // 在特定点查找主题
  const findTopicAtPoint = (x, y) => {
    return topics.value.find(
      (topic) => x >= topic.x && x <= topic.x + topic.width && y >= topic.y && y <= topic.y + topic.height,
    );
  };
  
  // 生成连接的 SVG 路径
  const generatePath = (connection) => {
    const source = topics.value.find((t) => t.id === connection.sourceId);
    const target = topics.value.find((t) => t.id === connection.targetId);
  
    if (!source || !target) return "";
  
    const sourceX = source.x + source.width;
    const sourceY = source.y + source.height / 2;
    const targetX = target.x;
    const targetY = target.y + target.height / 2;
  
    const controlPointX = (sourceX + targetX) / 2;
  
    return `M ${sourceX} ${sourceY} C ${controlPointX} ${sourceY}, ${controlPointX} ${targetY}, ${targetX} ${targetY}`;
  };
  
  // 生成活动连接的 SVG 路径
  const generateActivePath = () => {
    if (!activeConnection.value.source) return "";
  
    const source = activeConnection.value.source;
    const sourceX = source.x + source.width;
    const sourceY = source.y + source.height / 2;
    const targetX = activeConnection.value.mouseX;
    const targetY = activeConnection.value.mouseY;
  
    const controlPointX = (sourceX + targetX) / 2;
  
    return `M ${sourceX} ${sourceY} C ${controlPointX} ${sourceY}, ${controlPointX} ${targetY}, ${targetX} ${targetY}`;
  };
  </script>
  
  <style lang="less" scoped>
  .mind-map-container {
    width: 100%;
    height: 100%;
    position: relative;
    font-family: Arial, sans-serif;
  
    .mind-map {
      width: 100%;
      height: 600px;
      background-color: #f9f9f9;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
  
    .toolbar {
      display: flex;
      gap: 16px;
      padding: 10px;
      background-color: #f0f0f0;
      border-bottom: 1px solid #ddd;
      align-items: center;
  
      .btn {
        background-color: #4CAF50;
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
  
        &:hover {
          background-color: #45a049;
        }
      }
    }
  
    .color-picker, .line-style {
      display: flex;
      align-items: center;
      gap: 8px;
    }
  
    .topic-rect {
      cursor: move;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
    }
  
    .topic-text {
      font-size: 14px;
      pointer-events: none;
    }
  
    .add-button, .connect-button {
      cursor: pointer;
    }
  
    .topic-input {
      border: none;
      background: transparent;
      font-size: 14px;
      color: #fff;
      outline: none;
      padding: 5px;
      margin: 0;
      font-family: Arial, sans-serif;
      resize: none;
      overflow: hidden;
    }
  
    @media (max-width: 768px) {
      .toolbar {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .mind-map {
        height: 400px;
      }
    }
  }
  </style>